<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          计划入库单信息
        </div>
      </template>
      <el-form :model="info" class="grids columnsLine4 demo-form-inline" label-width="100">
        <el-form-item label="入库计划单">
          {{info.planSn}}
        </el-form-item>
        <el-form-item label="计划入库日期">
          {{info.planDate}}
        </el-form-item>
        <el-form-item label="供应商">
          {{info.supplierName}}
        </el-form-item>
        <el-form-item label="关联调拨单" v-if="info.transferSn">
          {{info.transferSn}}
        </el-form-item>
        <el-form-item label="入库类型">
          {{counter.idString_format("receiptType",info.type)}}
        </el-form-item>
        <el-form-item label="状态">
          {{counter.idString_format("entryStatus",info.status)}}
        </el-form-item>
        <el-form-item label="创建人">
          {{info.createBy}}
        </el-form-item>
        <el-form-item label="创建时间">
          {{info.createTime}}
        </el-form-item>
        <el-form-item label="备注">
          {{info.remark}}
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-form :inline="true" :model="formInline" class="demo-form-inline grids columnsLine4">
            <el-form-item label="货物编码">
              <el-input v-model="formInline.cargoSn" placeholder="请输入货物编码" clearable />
            </el-form-item>
            <el-form-item label="货物名称">
              <el-input v-model="formInline.cargoName" placeholder="请输入货物名称" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">搜索</el-button>
              <el-button type="primary" @click="add" plain>新增</el-button>
              <el-button @click="init">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>

      <el-table :data="tableData.rows" style="width: 100%">
        <el-table-column type="index" />
        <el-table-column prop="batchNumber" label="批次号" align="center" min-width="150" />
        <el-table-column prop="cargoSn" label="货物编码" align="center" min-width="150" />
        <el-table-column prop="cargoName" label="货物名称" />
        <el-table-column prop="planNum" label="计划入库数量" min-width="120" align="center" />
        <el-table-column prop="realNum" label="实际入库数量" min-width="120" align="center" />
        <el-table-column prop="cargoUnit" label="单位">
          <template #default="scope">
            <selectUnit v-model="scope.row.cargoUnit" readonly="1"></selectUnit>
          </template>
        </el-table-column>
        <el-table-column prop="cargoWeight" label="重量（KG）" min-width="120" align="center" />
        <el-table-column prop="cargoVolume" label="体积(m³)" />
        <el-table-column prop="cargoSpec" label="规格" />
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template #default="scope">
            <el-button type="primary" text @click="handClick(scope.row,1)">编辑</el-button>
            <el-button type="primary" text @click="handClick(scope.row,2)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination v-if="tableData['total']" :total="tableData['total']" v-model:page="formInline.pageNum" v-model:limit="formInline.pageSize" @pagination="getData" />
    </el-card>

    <el-dialog v-model="dialogVisible" title="新增/编辑货物" width="800" :before-close="handleClose">
      <el-form :model="form" label-width="120" :rules="rules" ref="formEl">
        <el-form-item label="货物名称">
          <selectCargo v-model="form.cargoId" @fatherMethods="getDetail" :list="canSelectCargo" :val="canSelectCargo.length?'cargoId':'id'"></selectCargo>
        </el-form-item>
        <el-form-item label="货物编码">
          <el-input v-model="form.cargoSn" placeholder="请输入货物编码" clearable disabled />
        </el-form-item>
        <el-form-item label="单位">
          <selectUnit v-model="form.cargoUnit" disabled></selectUnit>
        </el-form-item>
        <el-form-item label="规格">
          <el-input v-model="form.cargoSpec" placeholder="请输入规格" clearable disabled />
        </el-form-item>
        <el-form-item label="批次号" prop="batchNumber">
          <div class="flex" style="width:100%">
            <el-select v-model="form.batchNumber" placeholder="请选择批次号" style="width: 100%" v-if="showType">
              <el-option v-for="item in nos" :key="item.id" :label="`${item.batchNumber} ${item.cargoName}`" :value="item.batchNumber" />
            </el-select>
            <el-input v-model="form.batchNumber" placeholder="请输入批次号" v-else clearable disabled style="width:100%" />
            <el-button type="primary" icon="Refresh" circle @click="changeType" />
          </div>
        </el-form-item>
        <el-form-item label="计划入库数量" prop="planNum">
          <el-input-number v-model="form.planNum" :min="0" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" :autosize="{ minRows: 4 }" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm">
            确 认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
//counter
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const { proxy } = getCurrentInstance();
import { onMounted } from "vue";
import { useRoute } from "vue-router";
const route = useRoute();
let id = computed(() => {
  return route.query.id;
});
let info = ref({});
let formInline = ref({
  pageNum: 1,
  pageSize: 10,
  inPlanId: "",
  cargoSn: "",
  cargoName: "",
});
let showType = ref(false);
let rules = ref({
  cargoId: [
    {
      required: true,
      message: "请输入货物编码",
      trigger: "blur",
    },
  ],
  batchNumber: [
    {
      required: true,
      message: "请输入批次号",
      trigger: "blur",
    },
  ],
  planNum: [
    {
      required: true,
      message: "请输入计划入库数量",
      trigger: "blur",
    },
  ],
});
let form = ref({
  inPlanId: "",
  batchNumber: "",
  cargoId: "",
  cargoSn: "",
  cargoName: "",
  planNum: null,
  cargoUnit: "",
  cargoSpec: "",
  cargoWeight: "",
  cargoVolume: "",
});
let tableData = ref({ total: 0 });
let dialogVisible = ref(false);
let loading = ref(false);
let nos = ref([]);
let canSelectCargo = ref([]); //可以被选择的货物

// 生命周期
onMounted(() => {
  getInfo();
  getData();
});

let getNo = async () => {
  let { data } = await proxy.$apis.inPlanDetailQuery({ inPlanId: id.value });
  nos.value = data;
};
let getInfo = async () => {
  let { data } = await proxy.$apis.inPlanDetail({ id: id.value });
  //如果有关联调拨号
  if (data.transferSn) {
    let { data } = await proxy.$apis.transferDetailQuery({
      transferId: 3,
    });
    canSelectCargo.value = data;
    console.log("商品", data);
  }
  info.value = data;
};
let getData = async () => {
  formInline.value.inPlanId = id.value;
  tableData.value = await proxy.$apis.inPlanDetailList(formInline.value);
  getNo();
};
let search = () => {
  formInline.value.pageNum = 1;
  getData();
};
let init = async () => {
  formInline.value = {
    pageNum: 1,
    pageSize: 10,
    inPlanId: id.value,
    cargoSn: "",
    cargoName: "",
  };
  getData();
};
let handleClose = () => {
  form.value = {
    inPlanId: id.value,
    batchNumber: "",
    cargoId: "",
    cargoSn: "",
    cargoName: "",
    planNum: null,
    cargoUnit: "",
    cargoSpec: "",
    cargoWeight: "",
    cargoVolume: "",
  };
  showType.value = true;
  proxy.$refs.formEl.resetFields();
  getData();
  dialogVisible.value = false;
};
let getDetail = (e) => {
  if (e) {
    form.value = proxy.$utils.formatFunction(e, { ...form.value });
    //关联了调拨单，里面有计划调拨数量
    if (canSelectCargo.value.length) {
      form.value.planNum = e.num;
    }
  } else {
    form.value.cargoId = "";
    form.value.cargoSn = "";
    form.value.cargoName = "";
    form.value.cargoUnit = "";
    form.value.cargoSpec = "";
    form.value.cargoWeight = "";
    form.value.cargoVolume = "";
  }
};
let submitForm = async () => {
  await proxy.$refs.formEl.validate((valid, fields) => {
    if (valid) {
      save();
    } else {
      for (let key in fields) {
        return proxy.$utils.showToast(fields[key][0].message, 0);
      }
    }
  });
};
let save = async () => {
  try {
    loading.value = true;
    form.value.inPlanId = id.value;
    if (form.value.id) {
      await proxy.$apis.inPlanDetailEdit(form.value);
    } else {
      await proxy.$apis.inPlanDetailAdd(form.value);
    }
    proxy.$utils.showToast("操作成功");
    handleClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
let handClick = async (row, num) => {
  switch (num) {
    case 1:
      form.value = proxy.$utils.formatFunction(row, { ...form.value });
      form.value.id = row.id;
      dialogVisible.value = true;
      break;
    case 2:
      let resp = await proxy.$utils.confirmTips(
        `是否确定删除货物为 "${row.cargoName}" 的数据`
      );
      if (!resp) return;
      await proxy.$apis.inPlanDetailRemove({ id: row.id });
      proxy.$utils.showToast("删除成功");
      getData();
      break;

    default:
      break;
  }
};
let add = () => {
  //form.value.batchNumber = setNumberNo();
  showType.value = true;
  dialogVisible.value = true;
};
let setNumberNo = () => {
  let time = proxy.$utils.dateTimeFormateFn(new Date());
  let no = proxy.$utils.removeChar(time, "-");
  return `RKHW-${id.value}-${no}-${Date.now()}`;
};
let changeType = () => {
  showType.value = !showType.value;
  if (showType.value) {
    form.value.batchNumber = "";
  } else {
    form.value.batchNumber = setNumberNo();
  }
};
</script>

<style lang="scss" scoped>
.box-card {
  margin: 20px;
  .demo-form-inline {
    .el-form-item {
      margin-bottom: 0 !important;
    }
  }
}
</style>
